package com.tablefood.action;

import javax.annotation.Resource; 
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tablefood.domain.ShopCart;
import com.tablefood.domain.ShopUser;
import com.tablefood.service.CartService;
import com.tablefood.service.UserService;
import com.tablefood.service.Impl.UserServiceImpl;
import com.tablefood.utils.PageUserBean;
import com.tablefood.utils.ResultUtils;
 

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserAction extends ActionSupport {

	//普通用户登录和注册
	private ShopUser user;
 
	private String repassword;//确定第二次密码
	private String error=" ";//错误信息
 
	//后台管理要用
	private PageUserBean pageUserBean; // 封装了分页信息和数据内容的pageBean
	private List<ShopUser> listUser;// 用于储存pageBean当中被封装的User信息
	private int page = 1; // 表示从网页中返回的当前页的值 默认为1 表示默认显示第一页内容
	private long userid;
	private String message; 
	private BufferedImage image;
 
	private String reNewPassword;  
 
	
	@Resource
	private UserService userService; 
	@Resource
	private CartService cartService;
	/*
	 * 用户注册
	 * */
	public String Register() throws Exception {
		
		//其余没有设值的部分 调用了无参的构造函数
		System.out.println("-----注册-------");
		System.out.println("从jsp中获取用户信息");
		System.out.println("用户名："+user.getUsername());
		System.out.println("第一次密码:"+user.getUserpass());
		System.out.println("第二次密码:"+repassword);
		System.out.println("用户邮箱："+user.getUseremail());
		System.out.println("两次密码是否相同:"+user.getUserpass().equals(repassword));
		
		if(user.getUserpass().equals(repassword)){
			System.out.println("检验无误，可以添加新的用户");
			ShopUser reUser; 
			System.out.println("开始添加"); 
			//进入userDao
			boolean is = userService.addUser(user);
			 
			if(is){ 
				System.out.println("注册成功");
				return SUCCESS;
			}else{
				System.out.println("注册失败");
				error="该用户名或邮箱已被注册";
				return INPUT;
			}
			
		}else{
			System.out.println("检查有误，注册失败");
			error="两次密码不一致";
			return INPUT;
		}
		
	}
	
	/*
	 * 用户登录
	 * */
	public String Login() throws Exception{
		
		HttpSession session = ServletActionContext.getRequest().getSession();
		
		ShopUser logUser = new ShopUser();//user 和  logUser 是不同的   这里的user会调用无参的构造函数 
		List<ShopUser> result = userService.searchUser(user.getUsername()); 
		
		if(result.size()>0){
			logUser = result.get(0);
		}else{
			logUser.setUserpass("null");
		} 
		
		System.out.println("查询放回的用户名："+logUser.getUsername());
		System.out.println("查询放回的密码："+logUser.getUserpass());
		
		if(logUser.getUserpass().equals(user.getUserpass())){
			
			System.out.println("---检查成功，可以登录---");
		 
			System.out.println("用户原来更新时间："+logUser.getUpdateTime());
			Timestamp updatetime=new Timestamp(System.currentTimeMillis());
			logUser.setUpdateTime(updatetime);
			System.out.println("用户现在更新时间："+logUser.getUpdateTime());
			userService.updateUser(logUser);
			 
			List<ShopCart> num = cartService.searchCartByUserid(Long.toString(logUser.getUserid()));
			
			if(num!=null){
				session.setAttribute("cartNum",num.size());
			}
			else
				session.setAttribute("cartNum",0);
			
			error = "";
			
			session.setAttribute("username", logUser.getUsername());
			session.setAttribute("userid",logUser.getUserid());
			 
			
			return SUCCESS;
		}else{
			System.out.println("检查失败，不可登录");
			error="用户名或密码错误，请重新检查！";
		 
			return INPUT;
		}
	}
	/*
	 * 用户注销
	 * */
	public String Quit() throws Exception{
		
		ActionContext ac = ActionContext.getContext();
		Map session = ac.getSession();
		session.clear();
		
		return SUCCESS;
	}
	
	 
	public String changePassword(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		
	    if(session.getAttribute("username")==null)  
		   return "Empty";
		else{
		  try{	
		   String username=session.getAttribute("username").toString();
		   ShopUser user=(ShopUser) userService.searchUser(username).get(0);     
		   user.setUserpass(reNewPassword);
		   userService.updateUser(user);
		   return SUCCESS;}catch(Exception e){return ERROR;}
		}
	}
	
	
	 
	 
	 
	
	//显示用户表
	public String userList() throws Exception {
		this.pageUserBean = userService.queryForPage(5, page);// 获取封装了分页信息和数据的pageBean
		this.listUser = this.pageUserBean.getList(); // 获取数据
		return SUCCESS;
	}
	
	//删除用户-更改用户权限
	public String userDel() throws Exception {

		// System.out.println(userid);
		if (userid == 0) {
			this.setMessage("删除失败");
			return ERROR;
		}

		if (userService.delUser(userid)) {
			this.pageUserBean = userService.queryForPage(5, page);// 获取封装了分页信息和数据的pageBean
			this.listUser = this.pageUserBean.getList(); // 获取数据
			this.setMessage("删除成功");
			return SUCCESS;
		} else {
			this.setMessage("删除失败");
			return ERROR;
		}
	}
	
	// 用户详细信息
	public String userDetail() throws Exception {

		if (userid == 0) {
			user = null;
			return SUCCESS;
		}

		this.user = userService.getUserByUserId(userid);
		 
		if (this.user != null) {
			return SUCCESS;
		}
		return ERROR;
	}
	
	//添加用户
	public String userAdd() throws Exception {

		// 获取post请求的数据
		Map<String, String> param = new HashMap<String, String>();
		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, String[]> params = request.getParameterMap();
		for (String key : params.keySet()) {
			String[] values = params.get(key);
			for (int i = 0; i < values.length; i++) {
				param.put(key, values[i]);

			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		if (param.get("name") == "" || param.get("email") == "" || param.get("password") == "") {
			map.put("status", -1);
			ResultUtils.toJson(ServletActionContext.getResponse(), map);
			return null;
		}
		
		// 检索名字有没有重复
		if(userService.checkUserName(param.get("name"))){
			map.put("status", -1);
			ResultUtils.toJson(ServletActionContext.getResponse(), map);
			return null;
		}

		// 实例化
		ShopUser user = new ShopUser();
		user.setUsername(param.get("name"));
		user.setUseremail(param.get("email"));
		user.setUserpass(param.get("password"));
		user.setStatus("1");
		
		if(userService.addUser(user)){
			map.put("status", 0);
		}else{
			map.put("status", -1);
		}

		ResultUtils.toJson(ServletActionContext.getResponse(), map);
		return null;
	}
	
	//更新用户
	public String userUpdate() throws Exception {

		// 获取post请求的数据
		Map<String, String> param = new HashMap<String, String>();
		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, String[]> params = request.getParameterMap();
		for (String key : params.keySet()) {
			String[] values = params.get(key);
			for (int i = 0; i < values.length; i++) {
				param.put(key, values[i]);

			}
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		if (param.get("id") == "" || param.get("name") == "" || param.get("email") == "" || param.get("password") == "") {
			map.put("status", -1);
			ResultUtils.toJson(ServletActionContext.getResponse(), map);
			return null;
		}
		
		this.userid = Long.parseLong(param.get("id"));
		ShopUser user = userService.getUserByUserId(this.userid);
	
		
		// 检索名字有没有重复
		if(userService.checkUserName(param.get("name")) && !user.getUsername().equals(param.get("name")) ){
			map.put("status", -1);
			ResultUtils.toJson(ServletActionContext.getResponse(), map);
			return null;
		}
		
		// 实例化
		user.setUsername(param.get("name"));
		user.setUseremail(param.get("email"));
		user.setUserpass(param.get("password"));
		user.setStatus("1");
		
		if(userService.updateUser(user)){
			map.put("status", 0);
		}else{
			map.put("status", -1);
		}

		ResultUtils.toJson(ServletActionContext.getResponse(), map);
		return null;
	}
	
	public ShopUser getUser() {
		return user;
	}
	public String getReNewPassword() {
		return reNewPassword;
	}
	public void setReNewPassword(String reNewPassword) {
		this.reNewPassword = reNewPassword;
	}
	public void setUser(ShopUser user) {
		this.user = user;
	}
	
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public String getRepassword() {
		return repassword;
	}
	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}
	public long getUserid() {
		return userid;
	}
	public void setUserid(long userid) {
		this.userid = userid;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public PageUserBean getPageUserBean() {
		return pageUserBean;
	}
	public void setPageUserBean(PageUserBean pageUserBean) {
		this.pageUserBean = pageUserBean;
	}
	public List<ShopUser> getListUser() {
		return listUser;
	}
	public void setListUser(List<ShopUser> listUser) {
		this.listUser = listUser;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	
	 
	public BufferedImage getImage() {
		return image;
	}
	public void setImage(BufferedImage image) {
		this.image = image;
	}
	public String getError() {
		return error;
	}
	public void setError(String error) {
		this.error = error;
	}

 
 
	
	
}
